package api

import (
	"fmt"
	"strings"
)

import (
	"gitee.com/changeden/jd-union-go-sdk/common"
)

type apiConfig struct {
	appKey        string
	appSecret     string
	serverAddress string
}

func NewApiConfig(appKey, appSecret string) *apiConfig {
	inst := &apiConfig{
		serverAddress: common.DefaultServer,
	}
	return inst.SetAppKey(appKey).SetAppSecret(appSecret)
}

func checkAppInfo(req string, msg string) (res string, err error) {
	res = strings.TrimSpace(req)
	if len(res) == 0 {
		err = fmt.Errorf(msg)
	}
	return res, err
}

func checkAppKey(appKey string) (res string, err error) {
	return checkAppInfo(appKey, "AppKey不能为空")
}

func checkAppSecret(appSecret string) (res string, err error) {
	return checkAppInfo(appSecret, "AppSecret不能为空")
}

func (c *apiConfig) SetAppKey(appKey string) *apiConfig {
	appKey, _ = checkAppKey(appKey)
	c.appKey = appKey
	return c
}

func (c *apiConfig) SetAppSecret(appSecret string) *apiConfig {
	appSecret, _ = checkAppKey(appSecret)
	c.appSecret = appSecret
	return c
}

func (c *apiConfig) Build() (inst *api, err error) {
	_, err = checkAppKey(c.appKey)
	if err != nil {
		return
	}
	_, err = checkAppSecret(c.appSecret)
	if err != nil {
		return
	}
	inst = newApi(c)
	return
}
